package com.kx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kx.bean.Car;
import com.kx.bean.ParkingSpace;
import com.kx.bean.Toll;
import com.kx.bean.User;
import com.kx.converter.DateConverter;
import com.kx.dao.CarMapper;
import com.kx.dao.ParkingSpaceMapper;
import com.kx.dao.TollMapper;
import com.kx.dao.UserMapper;
import com.kx.service.CarService;
import com.kx.vo.BarVO;
import com.kx.vo.CarBarVO;
import com.kx.vo.DataVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CarServiceImpl implements CarService {


    @Autowired
    private CarMapper carMapper;

    @Autowired
    private TollMapper tollMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ParkingSpaceMapper parkingSpaceMapper;

    @Override
    public DataVO<Car> findData(Integer page, Integer limit) {
        DataVO<Car> dataVO = new DataVO<>();
        //1、设置code
        dataVO.setCode(0);
        //2、设置msg
        dataVO.setMsg("");
        //3、设置count(如果使用了mybatis-plus分页，则不需要调用其中selectCount方法单独调用)
//        dataVO.setCount(UserMapper.selectCount(null));
//        List<User> UserList= UserMapper.selectList(null);
        //取消上方全查询，分页设置List<User>通过getRecords()获取
        IPage<Car> carIPage = new Page<>(page, limit);
        IPage<Car> result = carMapper.selectPage(carIPage, null);
        dataVO.setCount(result.getTotal());
        List<Car> carList = result.getRecords();
        //4、设置data
        dataVO.setData(carList);
        return dataVO;
    }

    @Override
    public BarVO getBarVO() {
        List<CarBarVO> list = carMapper.findAllCarBarVO();
        List<Date> names = new ArrayList<>();
        List<Integer> values = new ArrayList<>();
        for (CarBarVO carBarVO : list) {
            names.add(carBarVO.getName());
            values.add(carBarVO.getCount());
        }
        BarVO barVO = new BarVO();
        barVO.setNames(names);
        barVO.setValues(values);
        return barVO;
    }

    @Override
    public List<CarBarVO> getPieVO() {
        return carMapper.findAllCarBarVO();
    }

    @Override
    public Car findCarByLicensePlate(String licensePlate) {
        QueryWrapper<Car> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("license_plate", licensePlate);
        return carMapper.selectOne(queryWrapper);
    }

    @Override
    public Car findById(Integer cid) {
        return carMapper.selectByPrimaryKey(cid);
    }

    @Override
    public int updateByLicensePlateEnter(Car car) {
        UpdateWrapper<Car> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("license_plate", car.getLicensePlate());
        if (Integer.parseInt(car.getInOutStatus()) == 0) {  //入场状态&&存在车主已预订车位
            car.setInOutStatus("1");
            car.setCreateTime(new Date());
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("cid", car.getCid());
            User user = userMapper.selectOne(queryWrapper);
            car.setRemark(String.valueOf(user.getPid()));
        } else {
            return 0;
        }
        return carMapper.update(car, updateWrapper);
    }

    @Override
    public int updateByLicensePlateOut(Car car) {
        UpdateWrapper<Car> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("license_plate", car.getLicensePlate());
        int price = 0;
        if (Integer.parseInt(car.getInOutStatus()) == 1) {
            Date d = new Date();
            car.setUpdateTime(d);
            Toll toll = new Toll();
            toll.setCid(car.getCid());
            toll.setPid(Integer.valueOf(car.getRemark()));
            toll.setIntoParkingTime(car.getCreateTime());
            toll.setOutParkingTime(d);
//            Car{cid=2, uid=1002, licensePlate='浙H18888', inOutStatus='1', packingFee=0, paymentStatus='未支付', createTime=Sun Mar 20 00:00:00 CST 2022, updateTime=Sat Mar 26 20:32:14 CST 2022, remark=''}
//            Sat Mar 26 20:32:14 CST 2022
//            int l = (int) DateConverter.myConvert2long(car1.getUpdateTime().toString());
            long l = DateConverter.curTimeMillis();
            long l1 = DateConverter.myConvert2long(car.getCreateTime().toString());
//            System.out.println(l - l1);
//            System.out.println((l - l1) / (24 * 60 * 60 * 1000)); //天
//            System.out.println((l - l1) / (60 * 60 * 1000));    //小时
//            System.out.println((l - l1) / (60 * 1000));   //分钟
            int hours = (int) ((l - l1) / (60 * 60 * 1000));
            if (hours < 1) {
                toll.setTotalCost(0);
                toll.setRemark("已支付");
                tollMapper.insert(toll);
                car.setInOutStatus("0");
                carMapper.update(car, updateWrapper);
            } else {
                price = hours * 2;
                toll.setTotalCost(price);
                int result = tollMapper.insert(toll) > 0 ? toll.getFid() : null;
                QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("cid", car.getCid());
                User user = userMapper.selectOne(queryWrapper);
                System.out.println(user);
                if (user.getWallet() > price) {
                    user.setPid(null);
                    int wallet = user.getWallet() - price;
                    user.setWallet(wallet);
                    UpdateWrapper<User> wrapper = new UpdateWrapper<>();
                    wrapper.eq("uid", user.getUid());
                    userMapper.update(user,wrapper);
                    car.setInOutStatus("0");
                    carMapper.update(car, updateWrapper);
                    toll.setRemark("已支付");
                    UpdateWrapper<Toll> updateWrapper1 = new UpdateWrapper<>();
                    updateWrapper1.eq("fid", result);
                    tollMapper.update(toll, updateWrapper1);
                    QueryWrapper<ParkingSpace> queryWrapper1 = new QueryWrapper<>();
                    queryWrapper1.eq("parking_number",car.getRemark());
                    ParkingSpace space = parkingSpaceMapper.selectOne(queryWrapper1);
                    UpdateWrapper<ParkingSpace> updateWrapper2 = new UpdateWrapper<>();
                    space.setParkingStatus("0");
                    updateWrapper2.eq("parking_number",car.getRemark());
                    parkingSpaceMapper.update(space,updateWrapper2);
                } else {
                    return 0;
                }
                return price;
            }
        }
        return price;
    }

    @Override
    public int updateOnlyByLicensePlateOut(Car car) {
        int price = 0;
        UpdateWrapper<Car> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("license_plate", car.getLicensePlate());
        car.setInOutStatus("0");
        Date d = new Date();
        car.setUpdateTime(d);
        Toll toll = new Toll();
        toll.setCid(car.getCid());
        toll.setPid(Integer.valueOf(car.getRemark()));
        toll.setIntoParkingTime(car.getCreateTime());
        toll.setOutParkingTime(car.getUpdateTime());

        long l = DateConverter.curTimeMillis();     //上方调取的update的时间未持久化
        long l1 = DateConverter.myConvert2long(car.getCreateTime().toString());
        int hours = (int) ((l - l1) / (60 * 60 * 1000));
        if (hours < 1) {
            toll.setTotalCost(0);
            toll.setRemark("已支付");
            tollMapper.insertToll(toll);
        } else {
            price = hours * 2;
            toll.setTotalCost(price);
            tollMapper.insert(toll);
            return price;
        }
        return price;
    }

    @Override
    public int updateCarOut(Car car) {
        UpdateWrapper<Car> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("remark", "");
        return carMapper.update(car, updateWrapper);
    }

    @Override
    public int updateCar(Car car) {
        UpdateWrapper<Car> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("cid", car.getCid());
        return carMapper.update(car, updateWrapper);
    }

    @Override
    public int deleteCar(Integer cid) {
        return carMapper.deleteByPrimaryKey(cid);
    }

    @Override
    public int save(Car car) {
        return carMapper.insert(car);
    }


    @Override
    public int saveEnter(Car car) {
        car.setInOutStatus("1");
        QueryWrapper<ParkingSpace> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parking_status", 0).last("limit 1");
        ParkingSpace space = parkingSpaceMapper.selectOne(queryWrapper);
        car.setRemark(String.valueOf(space.getParkingNumber()));
        space.setParkingStatus("1");
        parkingSpaceMapper.updateByPrimaryKeySelective(space);
        return carMapper.insert(car);
    }

    @Override
    public int saveCarAndGetCid(Car car) {
        return carMapper.insert(car) > 0 ? car.getCid() : null;
    }

}
